package com.easylive.service.impl;

import java.util.*;

import javax.annotation.Resource;

import com.easylive.entity.enums.ResponseCodeEnum;
import com.easylive.entity.po.UserVideoSeriesVideo;
import com.easylive.entity.po.VideoInfo;
import com.easylive.entity.query.UserVideoSeriesVideoQuery;
import com.easylive.entity.query.VideoInfoQuery;
import com.easylive.exception.BusinessException;
import com.easylive.mappers.UserVideoSeriesVideoMapper;
import com.easylive.mappers.VideoInfoMapper;
import org.springframework.stereotype.Service;

import com.easylive.entity.enums.PageSize;
import com.easylive.entity.query.UserVideoSeriesQuery;
import com.easylive.entity.po.UserVideoSeries;
import com.easylive.entity.vo.PaginationResultVO;
import com.easylive.entity.query.SimplePage;
import com.easylive.mappers.UserVideoSeriesMapper;
import com.easylive.service.UserVideoSeriesService;
import com.easylive.utils.StringTools;
import org.springframework.transaction.annotation.Transactional;


/**
 * 用户合集表 业务接口实现
 */
@Service("userVideoSeriesService")
public class UserVideoSeriesServiceImpl implements UserVideoSeriesService {

	@Resource
	private UserVideoSeriesMapper<UserVideoSeries, UserVideoSeriesQuery> userVideoSeriesMapper;

	@Resource
	private VideoInfoMapper<VideoInfo, VideoInfoQuery> videoInfoMapper;

	@Resource
	private UserVideoSeriesVideoMapper<UserVideoSeriesVideo, UserVideoSeriesVideoQuery> userVideoSeriesVideoMapper;

	/**
	 * 根据条件查询列表
	 */
	@Override
	public List<UserVideoSeries> findListByParam(UserVideoSeriesQuery param) {
		return this.userVideoSeriesMapper.selectList(param);
	}

	/**
	 * 根据条件查询列表
	 */
	@Override
	public Integer findCountByParam(UserVideoSeriesQuery param) {
		return this.userVideoSeriesMapper.selectCount(param);
	}

	/**
	 * 分页查询方法
	 */
	@Override
	public PaginationResultVO<UserVideoSeries> findListByPage(UserVideoSeriesQuery param) {
		int count = this.findCountByParam(param);
		int pageSize = param.getPageSize() == null ? PageSize.SIZE15.getSize() : param.getPageSize();

		SimplePage page = new SimplePage(param.getPageNo(), count, pageSize);
		param.setSimplePage(page);
		List<UserVideoSeries> list = this.findListByParam(param);
		PaginationResultVO<UserVideoSeries> result = new PaginationResultVO(count, page.getPageSize(), page.getPageNo(), page.getPageTotal(), list);
		return result;
	}

	/**
	 * 新增
	 */
	@Override
	public Integer add(UserVideoSeries bean) {
		return this.userVideoSeriesMapper.insert(bean);
	}

	/**
	 * 批量新增
	 */
	@Override
	public Integer addBatch(List<UserVideoSeries> listBean) {
		if (listBean == null || listBean.isEmpty()) {
			return 0;
		}
		return this.userVideoSeriesMapper.insertBatch(listBean);
	}

	/**
	 * 批量新增或者修改
	 */
	@Override
	public Integer addOrUpdateBatch(List<UserVideoSeries> listBean) {
		if (listBean == null || listBean.isEmpty()) {
			return 0;
		}
		return this.userVideoSeriesMapper.insertOrUpdateBatch(listBean);
	}

	/**
	 * 多条件更新
	 */
	@Override
	public Integer updateByParam(UserVideoSeries bean, UserVideoSeriesQuery param) {
		StringTools.checkParam(param);
		return this.userVideoSeriesMapper.updateByParam(bean, param);
	}

	/**
	 * 多条件删除
	 */
	@Override
	public Integer deleteByParam(UserVideoSeriesQuery param) {
		StringTools.checkParam(param);
		return this.userVideoSeriesMapper.deleteByParam(param);
	}

	/**
	 * 根据SeriesId获取对象
	 */
	@Override
	public UserVideoSeries getUserVideoSeriesBySeriesId(Integer seriesId) {
		return this.userVideoSeriesMapper.selectBySeriesId(seriesId);
	}

	/**
	 * 根据SeriesId修改
	 */
	@Override
	public Integer updateUserVideoSeriesBySeriesId(UserVideoSeries bean, Integer seriesId) {
		return this.userVideoSeriesMapper.updateBySeriesId(bean, seriesId);
	}

	/**
	 * 根据SeriesId删除
	 */
	@Override
	public Integer deleteUserVideoSeriesBySeriesId(Integer seriesId) {
		return this.userVideoSeriesMapper.deleteBySeriesId(seriesId);
	}

	@Override
	public List<UserVideoSeries> getUserAllSeries(String userId) {
		List<UserVideoSeries> userVideoSeries = userVideoSeriesMapper.selectUserAllSeries(userId);
		List<UserVideoSeriesVideo> userVideoSeriesVideos = userVideoSeriesVideoMapper.selectSeriesVideoInfo(userId);

		if (userVideoSeries != null && userVideoSeries.size() > 0 && userVideoSeriesVideos != null && userVideoSeriesVideos.size() > 0) {
			userVideoSeries.forEach(i -> {
				userVideoSeriesVideos.forEach(j -> {
					if (Objects.equals(i.getSeriesId(), j.getSeriesId())) {
						i.setCover(j.getCover());
					}
				});
			});

		}

		return userVideoSeries;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void saveUserVideoSeries(UserVideoSeries bean, String videoIds) {
		if (bean.getSeriesId() == null && StringTools.isEmpty(videoIds)) {
			throw new BusinessException(ResponseCodeEnum.CODE_600);
		}

		if (bean.getSeriesId() == null) {
			// 新增的时候一定要校验，这个视频是不是自己发布的视频，不能将别人的视频添加到自己的合集中\
			/**
			 * 新增：操作两个表：user_video_series 和 user_video_series_video
			 */
			checkVideoIds(bean.getUserId(), videoIds);
			bean.setUpdateTime(new Date());
			// 拿到当前用户的合集最大的排序，+1，默认往后面加
			bean.setSort(userVideoSeriesMapper.selectMaxSort(bean.getUserId()) + 1);
			userVideoSeriesMapper.insert(bean);
			saveSeriesVideo(bean.getUserId(), bean.getSeriesId(), videoIds);
		} else {
			// 修改
			/**
			 * 只操作一个表
			 */
			UserVideoSeriesQuery userVideoSeriesQuery = new UserVideoSeriesQuery();
			userVideoSeriesQuery.setUserId(bean.getUserId());
			userVideoSeriesQuery.setSeriesId(bean.getSeriesId());
			// 表格中设置了这两个字段是联合主键，只需要根据这个修改即可，并且更新时间是timestamp类型，所以不同设置更新时间
			userVideoSeriesMapper.updateByParam(bean, userVideoSeriesQuery);
		}
	}

	private void checkVideoIds(String userId, String videoIds) {
		String[] videoIdsArr = videoIds.split(",");
		List<String> videoIdsList = new ArrayList<>();
        videoIdsList.addAll(Arrays.asList(videoIdsArr));
		VideoInfoQuery query = new VideoInfoQuery();
		query.setVideoIds(videoIdsList);
		List<VideoInfo> videoInfoList = videoInfoMapper.selectList(query);

		for (VideoInfo videoInfo : videoInfoList) {
			if (!Objects.equals(videoInfo.getUserId(), userId)) {
				throw new BusinessException(ResponseCodeEnum.CODE_600);
			}
		}
	}

	@Override
	public void saveSeriesVideo(String userId, Integer seriesId, String videoIds) {
		UserVideoSeries userVideoSeries = userVideoSeriesMapper.selectBySeriesId(seriesId);
		if (userVideoSeries == null || !Objects.equals(userVideoSeries.getUserId(), userId)) {
			throw new BusinessException(ResponseCodeEnum.CODE_600);
		}
		checkVideoIds(userId, videoIds);
		String[]  videoIdArr = videoIds.split(",");
		Integer sort = userVideoSeriesVideoMapper.selectMaxSort(seriesId);

		List<UserVideoSeriesVideo> insertList = new ArrayList<>();
		for (String videoId : videoIdArr) {
			UserVideoSeriesVideo userVideoSeriesVideo = new UserVideoSeriesVideo();
			userVideoSeriesVideo.setSeriesId(seriesId);
			userVideoSeriesVideo.setVideoId(videoId);
			userVideoSeriesVideo.setSort(++sort);
			userVideoSeriesVideo.setUserId(userId);
			insertList.add(userVideoSeriesVideo);
		}
		userVideoSeriesVideoMapper.insertOrUpdateBatch(insertList);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void deleteVideoSeries(String userId, Integer seriesId) {
		UserVideoSeriesQuery userVideoSeriesQuery = new UserVideoSeriesQuery();
		userVideoSeriesQuery.setUserId(userId);
		userVideoSeriesQuery.setSeriesId(seriesId);
		userVideoSeriesMapper.deleteByParam(userVideoSeriesQuery);

		UserVideoSeriesVideoQuery userVideoSeriesVideoQuery = new UserVideoSeriesVideoQuery();
		userVideoSeriesVideoQuery.setSeriesId(seriesId);
		userVideoSeriesVideoQuery.setUserId(userId);
		userVideoSeriesVideoMapper.deleteByParam(userVideoSeriesVideoQuery);
	}

	@Override
	public void changeVideoSeriesSort(String userId, String seriesIds) {
		String[] seriesIdArr = seriesIds.split(",");
		UserVideoSeriesQuery query = new UserVideoSeriesQuery();
		query.setUserId(userId);
		query.setSeriesIds(seriesIdArr);
		List<UserVideoSeries> userVideoSeriesList = userVideoSeriesMapper.selectList(query);
		if (userVideoSeriesList != null && userVideoSeriesList.size() != seriesIdArr.length) {
			throw new BusinessException(ResponseCodeEnum.CODE_600);
		}
		Integer sort = 0;
		List<UserVideoSeries> updateList = new ArrayList<>();
		for (String seriesId : seriesIdArr) {
			UserVideoSeries userVideoSeries = new UserVideoSeries();
			userVideoSeries.setSort(++sort);
			userVideoSeries.setUserId(userId);
			userVideoSeries.setSeriesId(Integer.valueOf(seriesId));
			updateList.add(userVideoSeries);
		}
		userVideoSeriesMapper.updateBatch(updateList);
	}

	@Override
	public List<UserVideoSeries> findVideoSeriesWithVideo(UserVideoSeriesQuery userVideoSeriesQuery) {
		return userVideoSeriesMapper.findVideoSeriesWithVideo(userVideoSeriesQuery);
	}
}